<template>
  <div class="example2" ref="scrollRef" @scroll="scrollHandle">
    <div :style="{ height: totalHeight + 'px' }">
      <div
        class="example_item"
        v-for="item in subData"
        :key="item.id"
        :style="{
          height: itemHeight + 'px',
          position: 'absolute',
          top: item.id * itemHeight + 'px'
        }"
      >
        {{ item.name }}
      </div>
    </div>
  </div>
</template>

<script>
  var allData = [];
  for (let index = 0; index < 500; index++) {
    allData.push({
      id: index,
      name: '行' + (index + 1)
    });
  }
  export default {
    name: '',
    props: {},
    components: {},
    data() {
      return {
        itemHeight: 40,
        allData: allData,
        start: 0,
        count: 0
      };
    },
    computed: {
      totalHeight() {
        return this.itemHeight * this.allData.length;
      },
      subData() {
        return this.allData.slice(this.start, this.start + this.count);
      }
    },
    created() {},
    mounted() {
      var scrollRef = this.$refs.scrollRef;
      this.count = Math.ceil(scrollRef.clientHeight / this.itemHeight);
    },
    methods: {
      scrollHandle(e) {
        var scrollRef = this.$refs.scrollRef;
        var scrollTop = scrollRef.scrollTop;
        this.start = Math.floor(scrollTop / this.itemHeight);
      }
    },
    watch: {},
    filters: {}
  };
</script>

<style scoped lang="scss">
  .example2 {
    width: 300px;
    height: 500px;
    background-color: #fff;
    border: 1px solid #e8e8e8;
    overflow-y: auto;
    position: relative;
  }
  .example_item {
    width: 100%;
    &:nth-child(even) {
      background-color: #e3e3e3;
    }
  }
</style>
